package transaction02;

import org.apache.commons.dbutils.DbUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.junit.Test;

import java.sql.Connection;

/**
 * DBUtils管理事务
 */
public class TransactionDemo02 {
    @Test
    public void testTransaction() {
        //1.创建QueryRunner对象
        QueryRunner qr = new QueryRunner();
        //2.利用QueryRunner的UPdate方法
        Connection conn = JDBCUtils.getConnection();
        try {
            conn.setAutoCommit(false);//相当于MySQL中的 START Transaction
            qr.update(conn, "UPDATE account SET money = money + ? WHERE name = ?", -1000, "zhangsan");
//            int i = 2 / 0;
            qr.update(conn, "UPDATE account SET money = money + ? WHERE name = ?", 1000, "lisi");
            //提交操作
            DbUtils.commitAndCloseQuietly(conn);
        } catch (Exception e) {
            DbUtils.rollbackAndCloseQuietly(conn);//有异常则回滚数据
            e.printStackTrace();
        }
    }
}
